﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using nelech.Models.DBModel;

namespace nelech.Controllers.Utils
{
    public class AdvertControllerUtils
    {
        nelechDBEntities db = new nelechDBEntities();

        public static int GetAdvertCount(int advertPlace, int? region, nelechDBEntities db)
        {
            var adverts = db.Advert.AsEnumerable().Where(p => p.publish == 1 && p.date > DateTime.Now).ToList();
            var adverts1 = new List<Advert>();
            foreach (var a in adverts)
            {
                a.AdvertPlace.Load();
                a.Regeon.Load();
                if (region.HasValue)
                {
                    if (a.AdvertPlace.Any(p => p.id == advertPlace) && a.Regeon.Any(p => p.id == region || p.id == 21))
                        adverts1.Add(a);
                }
                else
                {
                    if (a.AdvertPlace.Any(p => p.id == advertPlace))
                        adverts1.Add(a);
                }

            }
            return adverts1.Count();
        }

        public static int[] GetUniqueArray(int count)
        {
            var rnd = new Random((int)DateTime.Now.Ticks);
            int[] arr;
            switch (count)
            {
                case 0:
                    return null;
                case 1:
                    arr = new int[1];
                    arr[0] = 0;
                    return arr;
                case 2:
                    arr = new int[2];
                    arr[0] = 0;
                    arr[1] = 1;
                    return arr;
                default:
                    arr = new int[3];
                    arr[0] = rnd.Next(0, count - 1);
                    if (arr[0] > 0 && arr[0] < count - 1)
                    {
                        arr[1] = rnd.Next(0, arr[0] - 1);
                        arr[2] = rnd.Next(arr[0] + 1, count - 1);
                        return arr;
                    }
                    if(arr[0] == 0)
                    {
                        arr[1] = rnd.Next(1, count - 1);
                        arr[2] = arr[1] < count - 1 ? rnd.Next(arr[1] + 1, count - 1) : rnd.Next(1, count - 2);
                        return arr;
                    }
                    arr[1] = rnd.Next(0, count - 2);
                    arr[2] = arr[1] < count - 2 ? rnd.Next(arr[1] + 1, count - 2) : rnd.Next(1, count - 3);
                    return arr;
            }
        }
    }
}